package com.juyu.miliao.api.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.juyu.miliao.api.domain.RedPacket;
import com.juyu.miliao.api.service.RedPacketService;
import com.juyu.miliao.api.validator.ComputeRedPacket;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.exception.IllegalParamException;

/**
 * 幸运红包功能
 *
 * @author wbf
 *
 */
@RestController
@RequestMapping("/redPacket")
public class RedPacketController {
	@Resource
	RedPacketService redPacketService;

	/**
	 * 获取幸运红包消费记录
	 *
	 * @param id
	 * @return
	 */
	@GetMapping("/{id:^[1-9][0-9]*$}/{page}-{pageSize}")
	public List<RedPacket> getRedPacket(Authentication token, @PathVariable("id") Integer id,
			@PathVariable("page") Integer page, @PathVariable("pageSize") Integer pageSize) {
		Subject subject = (Subject) token.getPrincipal();
		if (subject.getId() != id)
			throw new IllegalParamException("用户id错误");
		if (page <= 0) {
			page = 1;
		}
		if (pageSize <= 0) {
			pageSize = 20;
		}
		return redPacketService.getRedPacketById(id, page, pageSize);
	}

	/**
	 * 幸运红包业务逻辑
	 *
	 * @param entity
	 * @return
	 */
	@PostMapping()
	public RedPacket computeRedPacket(Authentication token, @Validated(ComputeRedPacket.class) RedPacket entity) {
		Subject subject = (Subject) token.getPrincipal();
		if (subject.getId() != entity.getUserId())
			throw new IllegalParamException("用户id错误");
		return redPacketService.computeRedPacket(entity);
	}

}
